package com.daiyang.blog.common.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtParserBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.io.Decoders;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;

import javax.crypto.SecretKey;
import java.time.Instant;
import java.util.Date;
import java.util.Map;

@Slf4j
public class JWTUtils {
    //密钥
    public static String secret="dVnsmy+SIX6pNptQdeclDSJ26EMSPEIhvZYKBTTug4k=";
    //过期时间
    public static long expiration=1000*60*60*24*7;
    //生产安全密钥
    public static SecretKey KEY= Keys.hmacShaKeyFor(Decoders.BASE64.decode(secret));
    /**
     * 生成token/生产令牌密钥
     * @param claims  载荷信息
     * @return
     */
    public static String genToken(Map<String, Object> claims) {
        String jwt= Jwts.builder().setClaims(claims)//自定义
                .setIssuedAt(new Date())//生成时间
                .setExpiration(new Date(System.currentTimeMillis() + expiration) )//过期时间
                .signWith(KEY).compact();//生产签名
        return jwt;
    }

    /**
     * 解析token/解析令牌密钥
     * @param jwt
     * @return
     */
    public static Map<String, Object> parseToken(String jwt) {
        if(!StringUtils.hasLength(jwt)){
            return null;
        }
        //创造解析器，设置签字密钥
        JwtParserBuilder jwtParserBuilder =
                Jwts.parserBuilder().setSigningKey(KEY);
        Claims claims =null;
        try {
            //解析
            claims = jwtParserBuilder.build().parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
           log.error("解析token失败：{}",jwt);
        }
        return claims;
    }

}
